package com.bearsadmin.controller;

import com.bearsadmin.common.Result;
import com.bearsadmin.dto.LoginDTO;
import com.bearsadmin.dto.RegisterDTO;
import com.bearsadmin.dto.UserUpdateDTO;
import com.bearsadmin.service.UserService;
import com.bearsadmin.util.JwtUtil;
import com.bearsadmin.vo.UserVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author Bears Admin
 * @since 1.0.0
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginDTO loginDTO) {
        String token = userService.login(loginDTO);

        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("tokenType", "Bearer");

        return Result.success("登录成功", data);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<UserVO> register(@Valid @RequestBody RegisterDTO registerDTO) {
        UserVO userVO = userService.register(registerDTO);
        return Result.success("注册成功", userVO);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/current")
    public Result<UserVO> getCurrentUser(@RequestHeader("Authorization") String token) {
        // 去掉Bearer前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        Long userId = JwtUtil.getUserId(token);
        UserVO userVO = userService.getUserById(userId);
        return Result.success("获取用户信息成功", userVO);
    }

    /**
     * 更新当前用户信息
     */
    @PutMapping("/current")
    public Result<UserVO> updateCurrentUser(
            @RequestHeader("Authorization") String token,
            @Valid @RequestBody UserUpdateDTO userUpdateDTO) {
        // 去掉Bearer前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        Long userId = JwtUtil.getUserId(token);
        UserVO userVO = userService.updateUser(userId, userUpdateDTO);
        return Result.success("更新用户信息成功", userVO);
    }

    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/{id}")
    public Result<UserVO> getUserById(@PathVariable Long id) {
        UserVO userVO = userService.getUserById(id);
        return Result.success("获取用户信息成功", userVO);
    }
}